package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.goods

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.RadioGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.databinding.DataBindingUtil.getBinding
import androidx.databinding.ViewDataBinding
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.db.GoodsDetailMsBean
import com.example.library_common.db.UserDatabase
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_LIST
import com.example.library_common.utils.normalShortToast
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.agency.bean.AreaItemBean
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.AddressSpot
import com.example.shushiyunsst.util.*

import com.example.wallet.db.UserInfoManager
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import ikidou.reflect.TypeBuilder
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.lang.StringBuilder
import java.lang.reflect.Type
import java.util.zip.Inflater


@Route(path = CONFIRM_TAKE_ORDER)
class ConfirmTakeOrderFragment : SimpleListFragment<GoodsDetailMsBean>(), View.OnClickListener,
    RadioGroup.OnCheckedChangeListener {


    private val shopCarBean = UserDatabase.getInstance()
        .shopCarBean()

    private val user = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo


    private lateinit var allGoodCountTv: TextView

    private val deliveryInfo = DeliveryInfoFragment.newInstance()

    private var mDeliveryInfoAgency = DeliveryInfoAgencyFragment.newInstance()

    private val childFragment = arrayOf<BaseFragmentEx>(
        deliveryInfo, mDeliveryInfoAgency
    )

    private var deliveryCost: TextView? = null

    private var allCostTv: TextView? = null

    private var orderDesc: EditText? = null

    private var toBuy: TextView? = null

    private var icon = AppGlobals.getApplication().getString(R.string.wallet_sst)

    private var payWay: RadioGroup? = null

    private var addressType: RadioGroup? = null

    private var currentIndex = 0

    private var lastIndex = 0

    private var mAgencyAddress:TextView?=null

    private val selectedAreaLs = mutableListOf<AreaItemBean?>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        isAlwaysRefresh = false
        isAddDividerItemDecoration = false
        isEnableLoadMore = false
    }

    override fun getItemLayout() = R.layout.confirm_take_order_fragment

    override fun convertItem(helper: JssBaseViewHolder?, item: GoodsDetailMsBean?) {
        helper?.setImageNetUrl(R.id.icon, item?.defaultImg)
            ?.setText(R.id.goodsName, item?.goodsName)
            ?.setText(
                R.id.goodsTyp,
                _mActivity.getString(
                    R.string.goodsTypeStr,
                    item?.defaultSelectColorLab(), item?.defaultSelectSizeLab()
                )
            )
            ?.setText(R.id.goodsPrice, "${item?.goodsPrice.toString()} $icon")
            ?.setText(R.id.goodsCount, "×${item?.selectedCount}")
    }

    override fun initView(view: View) {
        super.initView(view)
        view.setBackgroundResource(R.color.bg_color)
        mHeader.removeAllViews()
        payWay = view.findViewById(R.id.payWay)
        mHeader.setBackgroundResource(R.color.bg_color_0)
        addHeader(R.layout.comment_header_layout)
        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.setTitle(R.string.confirm_take_order)
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        addHeader(R.layout.confirm_take_order_header_fragment)

        addressType = mHeader.findViewById(R.id.addressType)

        addressType?.setOnCheckedChangeListener(this)
//        loadRootFragment(R.id.mDeliveryContainer, deliveryInfo)
        loadMultipleRootFragment(R.id.mDeliveryContainer, currentIndex, *childFragment)


        allGoodCountTv = mHeader.findViewById(R.id.allGoodCountTv)

        val orderListFooter = LayoutInflater.from(_mActivity)
            .inflate(R.layout.confirm_take_order_list_footer, view as ViewGroup, false)
        mAdapter.addFooterView(orderListFooter)

        mAgencyAddress=orderListFooter.findViewById(R.id.mAgencyAddress)
        mAgencyAddress?.setOnClickListener(this)

        deliveryCost = orderListFooter.findViewById(R.id.deliveryCost)
        orderDesc = orderListFooter.findViewById(R.id.orderDesc)

        mFooter.removeAllViews()
        addFooter(R.layout.confirm_take_order_footer)

        allCostTv = mFooter.findViewById(R.id.allCostTv)
        toBuy = mFooter.findViewById(R.id.toBuy)

        toBuy?.setOnClickListener(this)

    }


    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(GoodsDetailMsBean::class.java).endSubType().build()
    }

    @SuppressLint("SetTextI18n")
    override fun netRequest() {
        val cache = shopCarBean
            .getCache(user?.uid)

        loadListDate(cache?.shopCarList22)

        allGoodCountTv.text = "共${mAdapter.data.size}件商品"

        var allCostStr = 0
        for (e in mAdapter.data) {
            allCostStr += e.goodsPrice * e.selectedCount + e.goodsFare
        }

        allCostTv?.text = "$allCostStr $icon"
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.mAgencyAddress->{
                XPopup.Builder(_mActivity)
                    .asCustom(
                        SelectLocationPop(_mActivity)
                            .setIsAfterDistrict(true)
                            .setOnSelectListener(object : SelectLocationPop.OnSelectListener {

                                override fun onSelected(ls: List<AreaItemBean?>) {
                                    selectedAreaLs.clear()
                                    selectedAreaLs.addAll(ls)
                                    mAgencyAddress?.text = getSelectLocationName()
                                }
                            })
                    )
                    .show()
            }
            R.id.add_address_for_goods -> {
                ARouter.getInstance()
                    .build(ADD_DELIVERY_INFO)
                    .startNavigation(this)
            }

            R.id.addMore -> {
                ARouter.getInstance()
                    .build(ADD_DELIVERY_INFO_HISTORY)
                    .startNavigation(this)
            }

            R.id.toBuy -> {
                showPop()
//                toBuyNow()
            }

        }
    }

    private fun getSelectLocationName(): String {

        var string = StringBuilder()
        for (e in selectedAreaLs) {
            string.append(e?.areaName?.replace(",", "")).append(",")
        }

        if (string.lastIndexOf(",") != string.indexOf(",")) {
            string = string.deleteCharAt(string.lastIndexOf(","))
        }

        return string.toString()
    }

    private fun showPop() {
        val mPop = PayingPassWordVerifyPop(_mActivity)
        XPopup.Builder(_mActivity)
            .setPopupCallback(object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView?) {
                    super.onDismiss(popupView)
                    if (mPop.getIsOnVerifyPop()) {
                        if (mPop.getVerifyPop()) {
                            toBuyNow()
                        } else {
                            Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })
            .asCustom(mPop)
            .show()
    }

    private fun toBuyNow() {

//        val addressSpot = deliveryInfo.getAddressSpot()

        val addressSpot = when (addressType?.checkedRadioButtonId) {
            R.id.defaultAddress -> deliveryInfo.getAddressSpot()
            R.id.agencyAddress -> mDeliveryInfoAgency.getInfo()
            else -> deliveryInfo.getAddressSpot()
        }
        if (addressSpot == null) {

            normalShortToast(_mActivity, "请添加收货地址")

            return
        }

        if (addressSpot.msgStr.isNotEmpty()) {

            normalShortToast(_mActivity, addressSpot.msgStr)

            return
        }
        var goodsColor = StringBuilder()

        var goodsId = StringBuilder()

        var goodsNums = StringBuilder()

        var goodsSize = StringBuilder()

        for (e in mAdapter.data) {

            goodsColor.append(e.defaultSelectColorLab())
                .append(",")

            goodsId.append(e.gid)
                .append(",")

            goodsNums.append(e.selectedCount)
                .append(",")

            goodsSize.append(e.defaultSelectSizeLab())
                .append(",")
        }

        if (goodsColor.isNotEmpty()) {
            goodsColor = goodsColor.deleteCharAt(goodsColor.lastIndexOf(","))
        }
        if (goodsId.isNotEmpty()) {
            goodsId = goodsId.deleteCharAt(goodsId.lastIndexOf(","))
        }

        if (goodsNums.isNotEmpty()) {
            goodsNums = goodsNums.deleteCharAt(goodsNums.lastIndexOf(","))
        }
        if (goodsSize.isNotEmpty()) {
            goodsSize = goodsSize.deleteCharAt(goodsSize.lastIndexOf(","))
        }

        val user = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val payType = when (payWay?.checkedRadioButtonId) {
            R.id.fu_lu_ji_fen -> 1
            else -> 0
        }

        val aid = if (selectedAreaLs.isEmpty())
            "0"
        else
            "${selectedAreaLs[selectedAreaLs.size - 1]?.aid}"

        val map = mapOf(
            "areaIds" to addressSpot.areaIds,
            "goodsColor" to goodsColor.toString(),
            "goodsId" to goodsId.toString(),
            "goodsNums" to goodsNums.toString(),
            "goodsSize" to goodsSize.toString(),
            "orderDesc" to orderDesc?.text.toString(),
            "payType" to payType,
            "aid" to aid,
            "receiverAddr" to addressSpot.recAddr,
            "receiverName" to addressSpot.recName,
            "receiverPhone" to addressSpot.recPhone,
            "uId" to user?.uid,
        )

        RestClient.builder()
//            .url(R.string.saveShopCartOrder)
            .url(R.string.ys_saveShopCartOrder)
            .raw(JSON.toJSONString(map))
            .success {
                Toast.makeText(_mActivity, "下单成功", Toast.LENGTH_SHORT).show()
                shopCarBean.deleteAll()
                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_LIST))
                getUserBalanceInfo(_mActivity)
                onBackPressedSupport()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }
            .failure {
                Toast.makeText(_mActivity, "下单失败", Toast.LENGTH_SHORT).show()
            }.build().post()
    }

    override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
        when (checkedId) {
            R.id.defaultAddress -> {
                currentIndex = 0
            }
            R.id.agencyAddress -> {
                currentIndex = 1
            }
        }

        if (lastIndex == currentIndex) return

        val nextFragment = childFragment[currentIndex]

        showHideFragment(nextFragment, childFragment[lastIndex])

        lastIndex = currentIndex
    }

}